<?php

$data = "Un texto cualquiera que queremos encriptar...";

$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAMEBHbI7Y5psvSup9QDLRTAV3be8u6IOaKf8Ncxc3i0Pt0P2SwWd
LcGxx5xmEUlwJSp+DPC25K6KrcgtQnMlAzECAwEAAQJAeA64qUkWMVZY6lNjq2XG
mR3Q+N13Hly2L2DNGl3eespJHMk6Pp6zYH+5VxPww1rRmEOa6haFBLdyQyQOqN6O
kQIhAPRrLs2FCC/WOQPAy9IZozmFRw6cSZ8ve3zlNGzOavSVAiEAyiZGBhWUAYkd
KNDmfQHmOKUpz75StuRDueQYE6YJsS0CIQDx5cZLVtcUaQLCaSQPipoViocZuanP
ZvHjWQC6kswdxQIgTQnpBciTb0Jh6nwyWtGue0f2d0WBIFI9vUpAIrzUVMECIQCa
1BSGfBeqcL9SlQTqY4vVND8WXKh/TOP1ofONQWb8Ew==
-----END RSA PRIVATE KEY-----
EOD;

$public_key = <<<EOD
-----BEGIN PUBLIC KEY-----
MIIGEDCCBPigAwIBAgIQCXDetKLkjpAIibCxgH4SpTANBgkqhkiG9w0BAQUFADCB
tTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug
YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDEvMC0GA1UEAxMm
VmVyaVNpZ24gQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzMwHhcNMTEwNjEw
MDAwMDAwWhcNMTIwNjA5MjM1OTU5WjCB/DELMAkGA1UEBhMCQk8xEDAOBgNVBAgT
B01VUklMTE8xDzANBgNVBAcUBkxBIFBBWjERMA8GA1UEChQIRlVOREFQUk8xETAP
BgNVBAsUCFNJU1RFTUFTMTQwMgYDVQQLEytUZXJtcyBvZiB1c2UgYXQg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UlNlY3VyZUczLmNlcjBuBggrBgEFBQcBDARiMGChXqBcMFowWDBWFglpbWFn
ZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsHiyEFGDAmFiRodHRw
Oi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJKoZIhvcNAQEFBQAD
ggEBAA1DC2IBM9sWaz85uHj0XHpQS6HEHgVXozGT/IeyTxwsD7V8O2lghhK4eahg
v8B+VN3WYZipaTqR4ihUfKM92Bkzp1mp66AiVrNHPrEZWYCwt72TWBcGlaiiBDQL
biShukthfwEn6/bZTprK5pUgNR3AyTgMf5IkO+0cM2s7BQJ8gi147YlxHBXNIwjd
BdlVTh7b3nuSL8Rsqs88LJeA+8V/SunZJYZGBVEBZ92zTc3WSCQfpD9NlAtlZOcA
BDoYMLllcuQFWirYHjXj2VyeKeyAOdzvk8HQvCEz6/2JTgResd1nuf19rWT42mpq
BnoshVa1QqUx02twgnmFfDNSo/E=
-----END PUBLIC KEY-----
EOD;

$binary_signature = "";

//openssl_sign($data, $binary_signature, $private_key, OPENSSL_ALGO_SHA1);
openssl_sign($data, $binary_signature, $private_key);


// VERIFICAR FIRMA
//$ok = openssl_verify($data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
$ok = openssl_verify($data, $binary_signature, $public_key);

echo "Texto a encriptar: '$data' <br /><br />";
echo "Texto encriptado: $binary_signature <br /><br />";
echo "check #1: ";
if ($ok == 1) {
    echo "Firma correcta <br />";
} elseif ($ok == 0) {
    echo "Firma incorrecta <br />";
} else {
    echo "Error verificando la firma(1) <br />";
}

$dataModified = "'ALTERADO ".$data."'";
echo "<br /><br />Texto modificado: $dataModified <br /><br />";
//$ok = openssl_verify($dataModified, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
$ok = openssl_verify($dataModified, $binary_signature, $public_key);

echo "<br />check #2: ";
if ($ok == 1) {
    echo "ERROR: Los datos fueron alterados, pero la firma sigue siendo valida<br />";
} elseif ($ok == 0) {
    echo "Firma incorrecta (debido a que los datos fueron alterados)<br />";
} else {
    echo "Error verificando la firma(2)<br />";
}
